package safeCommitter.test.executor.launcher.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SCTestSocketWriter {
	private int port;
	private Socket socket;
	private PrintWriter writer;

	public SCTestSocketWriter(final int port) {
		this.port = port;
		openClientSocket();
	}

	public SCTestSocketWriter() {

	}

	private void openClientSocket() {
		for (int i = 0; i < 10; i++) {
			try {
				socket = new Socket("localhost", port);
				writer = new PrintWriter(socket.getOutputStream(), true);
				return;
			} catch (UnknownHostException e) {
			} catch (IOException e) {
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
			}
		}
	}

	public void closeClientSocket() {
		try {
			writer.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void write(final String string) {
		writer.write(string);
		writer.println();

	}
}
